/**
 * 获取仪表板统计数据
 */
exports.getDashboardStats = async (req, res) => {
  try {
    const db = require('../models');
    
    // 获取总用户数
    const totalUsers = await db.User.count({
      where: { role: { [db.Sequelize.Op.ne]: 'admin' } }
    });
    
    // 获取当前连接的用户数
    const connectedUsers = await db.WhatsappSession.count({
      where: { 
        status: 'connected',
        endTime: null
      }
    });
    
    // 获取总消息数
    const totalMessages = await db.Message.count();
    
    // 获取今日消息数
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const todayMessages = await db.Message.count({
      where: {
        createdAt: {
          [db.Sequelize.Op.gte]: today
        }
      }
    });
    
    res.json({
      totalUsers,
      connectedUsers,
      totalMessages,
      todayMessages
    });
  } catch (error) {
    console.error('获取仪表板统计数据失败:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

/**
 * 获取用户WhatsApp连接状态
 */
exports.getWhatsAppConnections = async (req, res) => {
  try {
    const db = require('../models');
    
    // 获取所有用户及其连接状态
    const users = await db.User.findAll({
      where: { role: { [db.Sequelize.Op.ne]: 'admin' } },
      include: [{
        model: db.WhatsappSession,
        as: 'whatsappSessions',
        where: { status: 'connected' },
        required: false,
        order: [['startTime', 'DESC']],
        limit: 1
      }],
      order: [['createdAt', 'DESC']]
    });
    
    const whatsappService = require('../services/whatsappService');
    
    const connections = users.map(user => {
      const latestSession = user.whatsappSessions?.[0];
      const connectionStatus = whatsappService.getConnectionStatus(user.id.toString());
      
      return {
        userId: user.id,
        username: user.username,
        fullName: user.fullName,
        role: user.role,
        status: connectionStatus.status || 'disconnected',
        phoneNumber: latestSession?.phoneNumber || null,
        connectedAt: latestSession?.startTime || null,
        lastActivity: latestSession?.lastActivity || null
      };
    });
    
    res.json(connections);
  } catch (error) {
    console.error('获取WhatsApp连接状态失败:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

/**
 * 获取最近活动
 */
exports.getRecentActivities = async (req, res) => {
  try {
    const db = require('../models');
    
    const activities = await db.ActivityLog.findAll({
      limit: 20,
      order: [['timestamp', 'DESC']],
      include: [{
        model: db.User,
        as: 'user',
        attributes: ['username', 'fullName']
      }]
    });
    
    const formattedActivities = activities.map(activity => ({
      id: activity.id,
      description: activity.description,
      type: activity.type,
      timestamp: activity.timestamp,
      username: activity.user?.username || '未知用户',
      fullName: activity.user?.fullName || '未知用户'
    }));
    
    res.json(formattedActivities);
  } catch (error) {
    console.error('获取最近活动失败:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

/**
 * 强制断开用户WhatsApp连接
 */
exports.forceDisconnectUser = async (req, res) => {
  try {
    const { userId } = req.params;
    
    const whatsappService = require('../services/whatsappService');
    const result = await whatsappService.disconnectWhatsApp(userId);
    
    if (result.success) {
      // 记录管理员操作
      const db = require('../models');
      await db.ActivityLog.create({
        userId: req.user.id,
        type: 'admin_action',
        description: `管理员强制断开用户 ${userId} 的WhatsApp连接`,
        metadata: { targetUserId: userId }
      });
      
      res.json({ success: true, message: '已成功断开用户连接' });
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    console.error('强制断开用户连接失败:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

/**
 * 获取系统健康状态
 */
exports.getSystemHealth = async (req, res) => {
  try {
    const db = require('../models');
    const whatsappService = require('../services/whatsappService');
    
    // 检查数据库连接
    let dbStatus = 'healthy';
    try {
      await db.sequelize.authenticate();
    } catch (error) {
      dbStatus = 'error';
    }
    
    // 检查WhatsApp服务状态
    const whatsappStatus = {
      totalClients: whatsappService.getActiveClientsCount?.() || 0,
      healthCheckRunning: whatsappService.sessionHealthCheck?.healthTimer !== null
    };
    
    // 检查内存使用情况
    const memoryUsage = process.memoryUsage();
    const memoryInfo = {
      rss: Math.round(memoryUsage.rss / 1024 / 1024), // MB
      heapUsed: Math.round(memoryUsage.heapUsed / 1024 / 1024), // MB
      heapTotal: Math.round(memoryUsage.heapTotal / 1024 / 1024), // MB
      external: Math.round(memoryUsage.external / 1024 / 1024) // MB
    };
    
    res.json({
      database: { status: dbStatus },
      whatsapp: whatsappStatus,
      memory: memoryInfo,
      uptime: Math.round(process.uptime()),
      timestamp: new Date()
    });
  } catch (error) {
    console.error('获取系统健康状态失败:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
}; 